<template>
  <div class="restaurant-detail-container">
    <!-- 餐厅头部信息 -->
    <div class="restaurant-header" v-if="restaurant">
      <div class="restaurant-info">
        <img :src="restaurant.image" :alt="restaurant.name" class="restaurant-image">
        <div class="restaurant-text">
          <h1>{{ restaurant.name }}</h1>
          <div class="rating">
            <i class="el-icon-star-on"></i>
            <span>{{ restaurant.rating }}</span>
            <span class="monthly-sales">月售 {{ restaurant.monthlySales }} 单</span>
          </div>
          <div class="restaurant-notice">
            <p>起送价 ¥{{ restaurant.minOrderAmount }} | 配送费 ¥{{ restaurant.deliveryFee }}</p>
            <p>营业时间: {{ restaurant.businessHours }}</p>
            <p>{{ restaurant.description }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 菜品列表 -->
    <div class="menu-container" v-loading="loading">
      <div class="menu-sidebar">
        <div 
          v-for="category in categories" 
          :key="category"
          :class="['category-item', activeCategory === category ? 'active' : '']"
          @click="scrollToCategory(category)"
        >
          {{ category }}
        </div>
      </div>

      <div class="menu-content" ref="menuContent">
        <div 
          v-for="category in categories" 
          :key="category"
          class="menu-category"
          :id="`category-${category}`"
        >
          <h3 class="category-title">{{ category }}</h3>
          <el-row :gutter="20" class="dish-list">
            <el-col :span="12" v-for="dish in getDishByCategory(category)" :key="dish.id">
              <el-card class="dish-card">
                <div class="dish-image">
                  <img :src="dish.image" :alt="dish.name">
                </div>
                <div class="dish-info">
                  <h4>{{ dish.name }}</h4>
                  <p class="dish-desc">{{ dish.description }}</p>
                  <div class="dish-sales">月售 {{ dish.sales }} 份</div>
                  <div class="dish-bottom">
                    <span class="dish-price">¥{{ dish.price }}</span>
                    <el-button
                      type="primary"
                      size="mini"
                      circle
                      icon="el-icon-plus"
                      @click="addToCart(dish)"
                      :disabled="dish.stock <= 0"
                    ></el-button>
                  </div>
                  <div class="dish-stock" v-if="dish.stock <= 5">
                    仅剩 {{ dish.stock }} 份
                  </div>
                  <div class="dish-stock sold-out" v-if="dish.stock <= 0">
                    已售罄
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 购物车 -->
      <div class="cart-container" v-if="cartList.length > 0">
        <div class="cart-header">
          <div class="cart-title">
            <i class="el-icon-shopping-cart-2"></i>
            <span>购物车</span>
            <span class="cart-count">({{ cartCount }})</span>
          </div>
          <el-button type="text" @click="clearCart">清空</el-button>
        </div>
        <div class="cart-items">
          <div v-for="item in cartList" :key="item.dish.id" class="cart-item">
            <div class="item-name">{{ item.dish.name }}</div>
            <div class="item-price">¥{{ item.dish.price * item.count }}</div>
            <div class="item-actions">
              <i class="el-icon-minus" @click="removeFromCart(item.dish.id)"></i>
              <span class="item-count">{{ item.count }}</span>
              <i class="el-icon-plus" @click="addToCart(item.dish)"></i>
            </div>
          </div>
        </div>
        <div class="cart-footer">
          <div class="cart-total">
            合计: <span class="total-price">¥{{ cartTotal }}</span>
          </div>
          <el-button 
            type="primary" 
            :disabled="cartTotal < restaurant.minOrderAmount"
            @click="checkout"
          >
            去结算
          </el-button>
          <div class="min-order-tip" v-if="cartTotal < restaurant.minOrderAmount">
            还差 ¥{{ (restaurant.minOrderAmount - cartTotal).toFixed(2) }} 起送
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'

export default {
  name: 'RestaurantDetail',
  data() {
    return {
      restaurant: null,
      menu: [],
      loading: true,
      activeCategory: '',
      categories: []
    }
  },
  computed: {
    ...mapGetters(['cartCount', 'cartTotal']),
    cartList() {
      return this.$store.state.cartList
    },
    restaurantId() {
      return this.$route.params.id
    }
  },
  created() {
    this.fetchRestaurantDetail()
    this.fetchMenu()
  },
  methods: {
    ...mapMutations(['ADD_TO_CART', 'REMOVE_FROM_CART', 'CLEAR_CART']),
    fetchRestaurantDetail() {
      this.$http.get(`/restaurant/${this.restaurantId}`)
        .then(response => {
          this.restaurant = response.data.data
        })
        .catch(error => {
          this.$message.error('获取餐厅详情失败')
          console.error('获取餐厅详情失败', error)
        })
    },
    fetchMenu() {
      this.loading = true
      this.$http.get(`/restaurant/${this.restaurantId}/menu`)
        .then(response => {
          this.menu = response.data.data
          // 提取所有分类
          const categorySet = new Set(this.menu.map(dish => dish.category))
          this.categories = Array.from(categorySet)
          if (this.categories.length > 0) {
            this.activeCategory = this.categories[0]
          }
        })
        .catch(error => {
          this.$message.error('获取菜单失败')
          console.error('获取菜单失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    getDishByCategory(category) {
      return this.menu.filter(dish => dish.category === category)
    },
    scrollToCategory(category) {
      this.activeCategory = category
      const element = document.getElementById(`category-${category}`)
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' })
      }
    },
    addToCart(dish) {
      if (dish.stock <= 0) return
      
      this.ADD_TO_CART({ 
        dish, 
        count: 1, 
        restaurantId: this.restaurantId,
        restaurantName: this.restaurant.name
      })
      this.$message.success(`已添加 ${dish.name} 到购物车`)
    },
    removeFromCart(dishId) {
      this.REMOVE_FROM_CART(dishId)
    },
    clearCart() {
      this.$confirm('确定清空购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.CLEAR_CART()
        this.$message.success('购物车已清空')
      }).catch(() => {})
    },
    checkout() {
      if (!this.$store.getters.isLoggedIn) {
        this.$router.push({
          path: '/login',
          query: { redirect: this.$route.fullPath }
        })
        return
      }
      
      this.$router.push('/order')
    }
  }
}
</script>

<style scoped>
.restaurant-detail-container {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.restaurant-header {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.restaurant-info {
  display: flex;
}

.restaurant-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 20px;
}

.restaurant-text h1 {
  margin: 0 0 10px 0;
}

.rating {
  color: #FF9900;
  margin-bottom: 10px;
}

.monthly-sales {
  color: #999;
  margin-left: 10px;
}

.restaurant-notice {
  font-size: 14px;
  color: #666;
}

.restaurant-notice p {
  margin: 5px 0;
}

.menu-container {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.menu-sidebar {
  width: 120px;
  border-right: 1px solid #eee;
  padding: 15px 0;
}

.category-item {
  padding: 10px 15px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.category-item:hover {
  color: #409EFF;
}

.category-item.active {
  color: #409EFF;
  background-color: #ecf5ff;
  border-left: 2px solid #409EFF;
}

.menu-content {
  flex: 1;
  padding: 15px;
  max-height: 600px;
  overflow-y: auto;
}

.category-title {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dish-list {
  margin-bottom: 20px;
}

.dish-card {
  margin-bottom: 20px;
  height: 100%;
  position: relative;
}

.dish-image {
  width: 100%;
  height: 120px;
  overflow: hidden;
}

.dish-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-info {
  padding: 10px 0;
}

.dish-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.dish-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
  height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.dish-sales {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.dish-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-price {
  color: #f56c6c;
  font-weight: bold;
}

.dish-stock {
  position: absolute;
  bottom: 10px;
  left: 10px;
  font-size: 12px;
  color: #E6A23C;
}

.dish-stock.sold-out {
  color: #F56C6C;
  font-weight: bold;
}

.cart-container {
  width: 300px;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-title {
  font-weight: bold;
}

.cart-count {
  color: #409EFF;
  margin-left: 5px;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  max-height: 400px;
  padding: 10px 15px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.item-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.item-price {
  margin: 0 10px;
  color: #f56c6c;
}

.item-actions {
  display: flex;
  align-items: center;
}

.item-actions i {
  cursor: pointer;
  color: #409EFF;
  padding: 2px 5px;
  border: 1px solid #dcdfe6;
  border-radius: 2px;
}

.item-count {
  width: 30px;
  text-align: center;
}

.cart-footer {
  padding: 15px;
  border-top: 1px solid #eee;
}

.cart-total {
  margin-bottom: 10px;
}

.total-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.min-order-tip {
  font-size: 12px;
  color: #E6A23C;
  margin-top: 5px;
  text-align: right;
}
</style>
